package com.quanyan.runningriding.service.impl;

import com.quanyan.api.APIResponse;
import com.quanyan.common.Plugin.PageObj;
import com.quanyan.runningriding.entity.db.*;
import com.quanyan.runningriding.entity.vo.run.MusicTypeVo;
import com.quanyan.runningriding.entity.vo.run.MusicVo;
import com.quanyan.runningriding.entity.vo.run.req.BatchSynchroniseMusic;
import com.quanyan.runningriding.entity.vo.run.resp.MusicType;
import com.quanyan.runningriding.entity.vo.run.resp.MyBelovedMusic;
import com.quanyan.runningriding.mapper.*;
import com.quanyan.runningriding.service.RunMusicService;
import com.quanyan.runningriding.util.RunEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import scala.collection.immutable.IntMapUtils;

import java.util.*;

/**
 * RunMusicServiceImpl
 *
 * @author Tu Chun
 * @date 2016/8/23
 */
@Service
public class RunMusicServiceImpl implements RunMusicService {
    @Autowired
    private TbRunMusicTypeMapper runMusicTypeMapper;

    @Autowired
    private RunMusicMapper runMusicMapper;

    @Autowired
    private TbRunMusicCollectMapper runMusicCollectMapper;

    @Autowired
    private TbRunMusicLibraryMapper runMusicLibraryMapper;

    @Autowired
    private TbRunMusicCollectionMapper tbRunMusicCollectionMapper;

    @Autowired
    private TbRunMusicCollectOperateRecordMapper tbRunMusicCollectOperateRecordMapper;

    @Override
    public APIResponse<List<MusicType>> getMusicTypeList() {
        List<MusicType> musicTypeList = runMusicMapper.getMusicTypeList();
        if (musicTypeList != null && musicTypeList.size() > 0) {
            for (int i = 0; i < musicTypeList.size(); i++) {
                MusicType musicType = musicTypeList.get(i);
                Integer typeId = musicType.getTypeId();
                switch (typeId) {
                    case 1:
                        musicType.setClassType("ico-run2");
                        break;
                    case 2:
                        musicType.setClassType("ico-run3");
                        break;
                    case 3:
                        musicType.setClassType("ico-run4");
                        break;
                    case 4:
                        musicType.setClassType("ico-run1");

                        break;
                }

            }
            //先保存最后一个对象
            MusicType musicType = musicTypeList.get(musicTypeList.size() - 1);
            musicTypeList.remove(musicTypeList.size() - 1);
            musicTypeList.add(0, musicType);
        }

        return APIResponse.returnSuccess(musicTypeList);
    }

    @Override
    public PageObj<List<MyBelovedMusic>> getMyBelovedMusicList(String userId, Integer pageNum, Integer pageSize) {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("userId", userId);
        paramMap.put("pageStart", (pageNum - 1) * pageSize);
        paramMap.put("pageSize", pageSize);
        List<MyBelovedMusic> myBelovedMusics = runMusicMapper.getMyBelovedMusicList(paramMap);
        Integer count = runMusicMapper.getMyBelovedMusicCount(userId);
        return PageObj.create(count, pageNum, pageSize, myBelovedMusics);
    }

    @Override
    public APIResponse<?> collectionMusic(String userId, Integer musicId, Byte operationType) {
        if (userId == null || "".equals(userId)) {
            return APIResponse.returnFail("用户id不能为空");
        }
        if (musicId == null || musicId == 0) {
            return APIResponse.returnFail("音乐id参数错误");
        }
        if (operationType == null || operationType == 0) {
            return APIResponse.returnFail("操作类型id参数错误");
        }
        TbRunMusicCollectExample tbRunMusicCollectExample = new TbRunMusicCollectExample();
        tbRunMusicCollectExample.createCriteria().andUserIdEqualTo(userId)
                .andMusicIdEqualTo(musicId);
        List<TbRunMusicCollect> runMusicCollects = runMusicCollectMapper.selectByExample(tbRunMusicCollectExample);
        Byte operation = 0;
        if (runMusicCollects != null && runMusicCollects.size() != 0) {
            operation = runMusicCollects.get(0).getIsCollect();
        }
        //操作类型 1收藏 2取消收藏
        if (operationType == 1) {

            if (operation == 1) {
                return APIResponse.returnSuccess("已经收藏此音乐");
            } else if (operation == 2) {
                TbRunMusicCollect runMusicCollect = new TbRunMusicCollect();
                runMusicCollect.setIsCollect((byte) 1);
                TbRunMusicCollectExample runMusicCollectExample = new TbRunMusicCollectExample();
                runMusicCollectExample.createCriteria().andMusicIdEqualTo(musicId).andUserIdEqualTo(userId);
                int i = runMusicCollectMapper.updateByExampleSelective(runMusicCollect, runMusicCollectExample);
                if (i <= 0) {
                    return APIResponse.returnFail("收藏失败");
                }
            } else {
                TbRunMusicLibrary tbRunMusicLibrary = runMusicLibraryMapper.selectByPrimaryKey(musicId);
                if (tbRunMusicLibrary == null) {
                    return APIResponse.returnFail("收藏的音乐不存在");
                }
                TbRunMusicCollect runMusicCollect = new TbRunMusicCollect();
                runMusicCollect.setUserId(userId);
                runMusicCollect.setMusicId(musicId);
                runMusicCollect.setIsCollect((byte) 1);
                int i = runMusicCollectMapper.insertSelective(runMusicCollect);
                if (i <= 0) {
                    return APIResponse.returnFail("收藏失败");
                }
            }

            return APIResponse.returnFail("收藏成功");

        } else if (operationType == 2) {
            if (runMusicCollects == null && runMusicCollects.size() == 0) {
                return APIResponse.returnFail("此音乐不存在");
            } else if (operation == 2) {
                return APIResponse.returnFail("你已取消收藏");
            }
            TbRunMusicCollect runMusicCollect = new TbRunMusicCollect();
            runMusicCollect.setIsCollect((byte) 2);
            TbRunMusicCollectExample runMusicCollectExample = new TbRunMusicCollectExample();
            runMusicCollectExample.createCriteria().andMusicIdEqualTo(musicId).andUserIdEqualTo(userId);
            int i = runMusicCollectMapper.updateByExampleSelective(runMusicCollect, runMusicCollectExample);
            if (i <= 0) {
                return APIResponse.returnFail("取消收藏失败");
            }
            return APIResponse.returnFail("取消收藏成功");
        }
        return APIResponse.returnFail("服务器异常");
    }

    @Override
    public APIResponse<MusicVo> getMusicByPace(Byte type, Integer cadence) {
        if (type == 1 || type == 2 || type == 3) {//不是自由跑按照类型推歌
            cadence = null;
        } else if (type == 4) {//自由跑 不传步频按照类型推 传步频按照步频推
            if (cadence != null) {
                type = null;
                if (cadence < 0) {
                    cadence = 0;
                }
                if (cadence > 180) {
                    cadence = 180;
                }
            } else {//如果为空随机取一种类型
                type = (byte) ((byte) (Math.random() * 3) + 1);
            }

        } else {
            APIResponse.returnFail(RunEnum.PARAMETER_NOT_VALID);
        }

        Map<String, Object> paramMap = new HashMap<String, Object>();

        paramMap.put("type", type);
        paramMap.put("cadence", cadence);

        List<MusicVo> musicVos = runMusicMapper.getMusicByPace(paramMap);
        if (musicVos != null && musicVos.size() > 0) {
            //随机挑选歌曲
            Integer random = new Double(Math.random() * musicVos.size()).intValue();
            MusicVo musicVo = musicVos.get(random);
            Integer musicBPM = musicVo.getMusicBPM() == null ? 0 : musicVo.getMusicBPM();
            List<Byte> types = new ArrayList<Byte>();
            types.add((byte)1);
            types.add((byte)2);
            types.add((byte)3);
            TbRunMusicTypeExample tbRunMusicTypeExample = new TbRunMusicTypeExample();
            tbRunMusicTypeExample.createCriteria().andMinCadenceLessThanOrEqualTo(musicBPM)
                    .andMaxCadence2GreaterThanOrEqualTo(musicBPM)
                    .andTypeIn(types);
            List<TbRunMusicType> tbRunMusicTypes= runMusicTypeMapper.selectByExample(tbRunMusicTypeExample);
            Integer pace=0;
            if (tbRunMusicTypes != null && tbRunMusicTypes.size() > 0) {
                TbRunMusicType tbRunMusicType= tbRunMusicTypes.get(0);
                Long minPace=tbRunMusicType.getMinPace();
                Long maxPace=tbRunMusicType.getMaxPace();
                Integer minCadence=tbRunMusicType.getMinCadence();
                Integer maxCadence=tbRunMusicType.getMaxCadence();
                if(musicBPM>maxCadence){

                    pace=musicBPM==minCadence?minPace.intValue():minPace.intValue()+(maxPace.intValue()-minPace.intValue())/(musicBPM-minCadence)*(musicBPM-minCadence);
                }else{
                    pace=minPace.intValue()+(maxPace.intValue()-minPace.intValue())/(maxCadence-minCadence)*(musicBPM-minCadence);

                }
            }
            musicVo.setAvgPace((long)pace);
            return APIResponse.returnSuccess(musicVo);
        } else {
            return APIResponse.returnFail("没有数据");
        }

    }

    @Override
    public APIResponse<?> batchUploadMusic(List<MusicVo> musicVos) {

        int reuslt = runMusicMapper.batchUploadMusic(musicVos);
        if (reuslt > 0) {
            return APIResponse.returnSuccess("批量上传音乐成功");
        } else {
            return APIResponse.returnSuccess("批量上传音乐失败");
        }

    }

    @Override
    public PageObj<List<MusicVo>> musicList(String name, String author, Byte type, Integer pageNum, Integer pageSize) {
        if (pageNum == null || pageNum == 0) {
            pageNum = 1;
        }
        if (pageSize == null || pageSize == 0) {
            pageSize = 20;
        }
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("pageStart", (pageNum - 1) * pageSize);
        paramMap.put("pageSize", pageSize);
        paramMap.put("name", name);
        paramMap.put("author", author);
        paramMap.put("type", type);

        List<MusicVo> musicVos = runMusicMapper.musicList(paramMap);
        Integer count = runMusicMapper.musicCount(paramMap);
        PageObj pageObj = PageObj.create(count, pageNum, pageSize, musicVos);
        return pageObj;
    }

    @Override
    public APIResponse<?> updateMusic(MusicVo musicVo) {
        TbRunMusicLibrary tbRunMusicLibrary = new TbRunMusicLibrary();
        tbRunMusicLibrary.setId(musicVo.getId());
        tbRunMusicLibrary.setAddressUrl(musicVo.getAddressUrl());
        tbRunMusicLibrary.setAuthorName(musicVo.getAuthor());
        tbRunMusicLibrary.setMusicTypeId(musicVo.getType());
        tbRunMusicLibrary.setMusicBpm(musicVo.getMusicBPM());
        tbRunMusicLibrary.setName(musicVo.getName());
        tbRunMusicLibrary.setSize(musicVo.getSize());
        tbRunMusicLibrary.setTime(musicVo.getTime());
        Integer i = runMusicLibraryMapper.updateByPrimaryKeySelective(tbRunMusicLibrary);
        if (i > 0)
            return APIResponse.returnSuccess("跟新成功");
        return APIResponse.returnFail("跟新异常");
    }

    @Override
    public APIResponse<?> deleteMusic(Integer musicId) {
        if (musicId == 0 || musicId == null) {
            APIResponse.returnFail("参数异常");
        }
        Integer i = runMusicLibraryMapper.deleteByPrimaryKey(musicId);
        if (i > 0)
            return APIResponse.returnSuccess("删除成功");
        return APIResponse.returnFail("删除异常");
    }

    @Override
    public APIResponse<MusicVo> getMusicById(Integer id) {
        List<MusicVo> musicVos = runMusicMapper.getMusicById(id);
        List<Byte> types = new ArrayList<Byte>();
        types.add((byte)1);
        types.add((byte)2);
        types.add((byte)3);
        if(musicVos == null || musicVos.size() <= 0)
            return APIResponse.returnFail("没有数据 ");
        MusicVo musicVo = musicVos.get(0);
        Integer musicBPM = musicVo.getMusicBPM() == null ? 0 : musicVo.getMusicBPM();
        TbRunMusicTypeExample tbRunMusicTypeExample = new TbRunMusicTypeExample();
        tbRunMusicTypeExample.createCriteria().andMinCadenceLessThanOrEqualTo(musicBPM)
                .andMaxCadence2GreaterThanOrEqualTo(musicBPM).andTypeIn(types);
        List<TbRunMusicType> tbRunMusicTypes= runMusicTypeMapper.selectByExample(tbRunMusicTypeExample);
        Integer pace=0;
        if (musicVos != null && musicVos.size() > 0) {
            TbRunMusicType tbRunMusicType= tbRunMusicTypes.get(0);
            Long minPace=tbRunMusicType.getMinPace();
            Long maxPace=tbRunMusicType.getMaxPace();
            Integer minCadence=tbRunMusicType.getMinCadence();
            Integer maxCadence=tbRunMusicType.getMaxCadence();
            if(musicBPM>maxCadence){
                pace=musicBPM==minCadence?minPace.intValue():minPace.intValue()+(maxPace.intValue()-minPace.intValue())/(musicBPM-minCadence)*(musicBPM-minCadence);
            }else{
                pace=minPace.intValue()+(maxPace.intValue()-minPace.intValue())/(maxCadence-minCadence)*(musicBPM-minCadence);

            }
            musicVo.setAvgPace((long)pace);
            return APIResponse.returnSuccess(musicVo);
        }
        return APIResponse.returnFail("没有数据 ");
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public APIResponse<?> batchCollectionMusic(List<BatchSynchroniseMusic> batchSynchroniseMusics) {
        //批量删除 防止重复
        Integer j = runMusicMapper.batchDeleteCollectionMusic(batchSynchroniseMusics);
        //批量提交
        Integer i = runMusicMapper.batchCollectionMusic(batchSynchroniseMusics);
        if (j > 0 && i > 0)
            return APIResponse.returnSuccess("批量同步音乐成功");
        else
            return APIResponse.returnFail("批量同步音乐失败");
    }

    @Override
    public APIResponse<?> editMusicType(MusicTypeVo musicTypeReq) {
        return null;
    }

    @Override
    public APIResponse<?> deleteMusicType(Byte musicType) {
        return null;
    }

    @Override
    public PageObj<List<MusicTypeVo>> musicTypeList(Byte type, String name, Double pace, Integer cadence, Integer pageNum, Integer pageSize) {
        return null;
    }

    @Override
    public APIResponse<List<MusicTypeVo>> getMusicTypeListAdmin() {
        return null;
    }

    @Override
    public APIResponse<?> musicCollectionOperate(String userId,Integer musicCollectionId, Byte operateType, Byte operateAction, Long playTime) {
        //操作类型 1喜欢 2播放 3缓存

        if (userId == null || "".equals(userId)){
            return APIResponse.returnFail("用户Id不能为空");
        }

        if (musicCollectionId == null || "".equals(musicCollectionId)){
            return APIResponse.returnFail("歌单Id不能为空");
        }
        TbRunMusicCollectOperateRecord tbRunMusicCollectOperateRecord=new TbRunMusicCollectOperateRecord();
        tbRunMusicCollectOperateRecord.setMusicCollectionId(musicCollectionId);
        tbRunMusicCollectOperateRecord.setOperateType(operateType);
        tbRunMusicCollectOperateRecord.setOperateAction(operateAction);
        tbRunMusicCollectOperateRecord.setUserId(userId);
        tbRunMusicCollectOperateRecord.setPlayTime(playTime);
        tbRunMusicCollectOperateRecord.setUpdateTime(new Date());
        //如果是喜欢或者缓存的时候记录只能有一条
        if (operateType == 1 || operateType==3){
            TbRunMusicCollectOperateRecordExample tbRunMusicCollectOperateRecordExample=new TbRunMusicCollectOperateRecordExample();
            tbRunMusicCollectOperateRecordExample.createCriteria().andUserIdEqualTo(userId).andMusicCollectionIdEqualTo(musicCollectionId).andOperateTypeEqualTo(operateType);
            List<TbRunMusicCollectOperateRecord> tbRunMusicCollectOperateRecords=tbRunMusicCollectOperateRecordMapper.selectByExample(tbRunMusicCollectOperateRecordExample);
            if (tbRunMusicCollectOperateRecords != null && tbRunMusicCollectOperateRecords.size() > 0) {
                //如果有记录则更新 没有添加
                tbRunMusicCollectOperateRecordMapper.updateByExampleSelective(tbRunMusicCollectOperateRecord,tbRunMusicCollectOperateRecordExample);
            }

        }

        tbRunMusicCollectOperateRecord.setCreateTime(new Date());
        int i=tbRunMusicCollectOperateRecordMapper.insertSelective(tbRunMusicCollectOperateRecord);
        if (i > 0) {
            return APIResponse.returnSuccess("歌单操作成功");
        }
        return APIResponse.returnFail("歌单操作失败");
    }
}
